<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <el-input
          v-model="filterText"
          placeholder="输入用户名过滤"
        />
        <el-tree
          ref="tree"
          accordion
          default-expand-all
          node-key="id"
          class="tree"
          :highlight-current="true"
          :expand-on-click-node="false"
          :data="users"
          :props="defaultProps"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        >
          <span slot-scope="{ node }" class="custom-tree-node">
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
      </el-col>
      <el-col :span="20" style="padding-left: 16px;">
        <el-row style="height: 180px;">
          <el-col :span="12">
            <el-card class="card">
              <div slot="header">
                <span>{{ currentUser.name }}</span>
                <span style="margin-left: 8px; color: #67C23A; font-size:12px">{{ '利率:' + currentUser.interest_rate + '%' }}</span>
                <span style="margin-left: 8px; color: #67C23A; font-size:12px">{{ '限额:' + currentUser.score + '元' }}</span>
                <el-button style=" padding: 0 0 0 16px" type="text" @click="dialogStoreVisible = true">商店管理</el-button>
                <el-button style=" padding: 0 0" type="text" @click="changeInterestRate">修改利率</el-button>
              </div>
              <el-row>
                <el-col :span="8">
                  <span style="font-size:14px; font-weight: bold;">跑分</span>
                  <div style="padding-top:8px">
                    <span style="font-size:11px;">当前跑分：{{ countInfo.currentScore /100 }}元</span>
                  </div>
                  <div>
                    <span style="font-size:11px;">当月跑分：{{ countInfo.periodScore /100 }}元</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <span style="font-size:14px; font-weight: bold;">利润</span>
                  <div style="padding-top:8px">
                    <span style="font-size:11px;">当前利润：{{ (countInfo.currentInterest / 10000).toFixed(2) }}元</span>
                  </div>
                  <div>
                    <span style="font-size:11px;">当月利润：{{ (countInfo.periodInterest / 10000).toFixed(2) }}元</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <span style="font-size:14px; font-weight: bold;">下级贡献</span>
                  <div style="padding-top:8px">
                    <span style="font-size:11px;">今日贡献：{{ (countInfo.todayRent / 10000).toFixed(2) }}元</span>
                  </div>
                  <div>
                    <span style="font-size:11px;">当月贡献：{{ (countInfo.periodRent / 10000).toFixed(2) }}元</span>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
          <el-col :span="12" style="padding-left: 16px;">
            <el-card class="card">
              <div slot="header">
                <span>记账日期：{{ '  '+ currentDate }}</span>
                <div style="display: inline-block; margin-left: 32px;font-size:14px;color:#79bbff">只显示：</div>
                <el-radio-group v-model="scoreInfo.type">
                  <el-radio label="开启" />
                  <el-radio label="所有" />
                </el-radio-group>
              </div>
              <el-row>
                <el-col :span="10">
                  <span class="score-info">总限额：{{ scoreInfo.type === '开启' ? scoreInfo.runScore : scoreInfo.allScore }} 元</span>
                </el-col>
                <el-col :span="7">
                  <span class="score-info score-info-current">总成功金额：{{ scoreInfo.type === '开启' ? scoreInfo.runSuccessScore : scoreInfo.allSuccessScore }} 元</span>
                </el-col>
                <el-col :span="7">
                  <span class="score-info score-info-current">剩余额度：{{ scoreInfo.type === '开启' ? scoreInfo.runScore - scoreInfo.runSuccessScore : scoreInfo.allScore - scoreInfo.allSuccessScore }} 元</span>
                </el-col>
              </el-row>
              <el-row style="padding-top: 24px;">
                <el-col :span="8">
                  <span class="score-info">今日总交易笔数：{{ todayOrder.orderNumber }} </span>
                </el-col>
                <el-col :span="8">
                  <span class="score-info">今日总成功笔数：{{ todayOrder.payNumber }} </span>
                </el-col>
                <el-col :span="8">
                  <span class="score-info">今日总成功率：{{ todayOrder.payRate? todayOrder.payRate.toFixed(2) : 0 }} %</span>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-row type="flex" align="bottom" justify="space-between">
              <el-col :span="8">
                <h5>店铺</h5>
              </el-col>
              <el-col :span="16">
                <div class="toop-bar">
                  <el-button-group>
                    <el-button size="mini" type="primary" @click="setScore">批量限额</el-button>
                    <el-button size="mini" type="primary" @click="startAll">全部开启</el-button>
                    <el-button size="mini" type="primary" @click="stopAll">全部结束</el-button>
                  </el-button-group>
                </div>
              </el-col>
            </el-row>
            <el-table
              v-loading="storeTableLoading"
              :data="stores"
              size="mini"
              border
              height="360px"
              highlight-current-row
              @row-click="handleStoreRowClick"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" />
              <el-table-column label="ID" align="center" min-width="17%">
                <template slot-scope="{row}">
                  <span>{{ row.id }}</span>
                </template>
              </el-table-column>
              <el-table-column label="店名" align="center" min-width="17%">
                <template slot-scope="{row}">
                  <span>{{ row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="商品数" align="center" min-width="12%">
                <template slot-scope="{row}">
                  <span>{{ row.goods_size }}</span>
                </template>
              </el-table-column>
              <el-table-column label="金额上限" align="center" min-width="14%">
                <template slot-scope="{row}">
                  <span>{{ row.score / 100 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="成交金额" align="center" min-width="14%">
                <template slot-scope="{row}">
                  <span>{{ row.used_score / 100 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="剩余金额" align="center" min-width="14%">
                <template slot-scope="{row}">
                  <span>{{ (row.score - row.used_score) / 100 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" min-width="13%" align="center" class-name="small-padding fixed-width">
                <template slot-scope="{row}">
                  <el-switch
                    v-model="row.loop"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="toggleStoreLoop(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="13%" align="center" class-name="small-padding fixed-width">
                <template slot-scope="{row}">
                  <el-tag size="mini" effect="dark" type="success" @click="handleEditStore(row)">修改</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="10" style="padding-left: 8px;">
            <h5>商品</h5>
            <el-table
              v-loading="goodsTableLoading"
              :data="goodses"
              size="mini"
              border
              height="360px"
              highlight-current-row
            >
              <el-table-column label="ID" align="center" min-width="30%">
                <template slot-scope="{row}">
                  <a
                    :href="'https://mobile.yangkeduo.com/goods.html?goods_id='+row.id"
                    target="_blank"
                    style="color: blue;"
                  >
                    {{ row.id }}
                  </a>
                </template>
              </el-table-column>
              <el-table-column label="价格" align="center" min-width="16%">
                <template slot-scope="{row}">
                  <span>{{ row.price / 100 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="轮询量" align="center" min-width="17%">
                <template slot-scope="{row}">
                  <span>{{ row.loop_times }}</span>
                </template>
              </el-table-column>
              <el-table-column label="成交量" align="center" min-width="17%">
                <template slot-scope="{row}">
                  <span>{{ row.done_times }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" min-width="20%">
                <template slot-scope="{row}">
                  <el-switch
                    v-model="row.loop"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="toggleGoodsLoop(row)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-dialog
      :visible.sync="dialogStoreVisible"
      title="店铺管理"
      @closed="handleDialogStoreClose"
    >
      <h3>用户：{{ currentUser.name }}</h3>
      <div>
        选择添加店铺：
        <el-select
          v-model="selectedValue"
          multiple
          filterable
          style="width: 300px;"
          remote
          reserve-keyword
          placeholder="请输入店铺ID"
          :remote-method="getSelectStore"
          :loading="selectLoading"
        >
          <el-option
            v-for="item in selectStores"
            :key="item.id"
            :label="item.id+'-'+item.name"
            :value="item.id"
          />
        </el-select>
        <el-button type="primary" @click="addStoresToUser">
          添加
        </el-button>
      </div>
      <div class="tag-wrapper">
        <el-tag v-for="item in stores" :key="item.id" class="tag-small" closable @close="removeStore(item.id)">
          {{ item.id }}-{{ item.name }}
        </el-tag>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogModifyStoreVisible"
      title="商店信息修改"
      width="40%"
    >
      <el-form label-width="80px" :model="formEditStore">
        <el-form-item label="限额">
          <el-input v-model="formEditStore.score" style="width:300px">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formEditStore.loop" placeholder="请设置状态" style="width:300px">
            <el-option label="生效" value="true" />
            <el-option label="无效" value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="formEditStore.userId" placeholder="请设置负责人" style="width:300px">
            <el-option
              v-for="item in allUser"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogModifyStoreVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFormEditStore">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { toTree, getCurrentDate } from '@/utils'
import { getAllUser, setInterestRate, fetchStore, startAllStore, stopAllStore, getCountInfo, setPause, setUserScore } from '@/api/user'
import { setLoop, setScore, setUserId, queryNoUserId, removeUserId, editStore } from '@/api/store'
import { getList as getGoodsList, setLoop as setGoodsLoop } from '@/api/goods'
import { info } from '@/api/score'
import { getUserOrderStatistic } from '@/api/statistic'
import { Message } from 'element-ui'
const dateFormat = require('dateformat')

export default {
  name: 'Role',
  data() {
    return {
      currentDate: getCurrentDate(),
      selectLoading: false,
      storeTableLoading: false,
      goodsTableLoading: false,
      dialogStoreVisible: false,
      dialogModifyStoreVisible: false,
      filterText: '',
      selectStores: [],
      selectedValue: [],
      users: [],
      allUser: [],
      parentUser: {},
      currentUser: {},
      noPidUsers: [],
      stores: [],
      goodses: [],
      multipleSelection: [],
      total: 0,
      todayOrder: {
        orderNumber: 0,
        payNumber: 0,
        payRate: 0
      },
      scoreInfo: {
        type: '开启',
        allScore: 0,
        allSuccessScore: 0,
        runScore: 0,
        runSuccessScore: 0
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      formAppend: {
        pid: '',
        id: ''
      },
      countInfo: {
        periodScore: 0,
        periodInterest: 0,
        currentScore: 0,
        currentInterest: 0,
        todayRent: 0,
        periodRent: 0
      },
      formEditStore: {
        score: 0,
        loop: 'false',
        old_loop: 'false',
        userId: '',
        storeId: ''
      }
    }
  },
  computed: mapGetters({
    rootUserId: 'id',
    roles: 'roles'
  }),
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    getAllUser().then(response => {
      const list = response.data
      this.allUser = list
      this.setUsers()
      this.$nextTick(() => this.$refs.tree.setCurrentKey(this.rootUserId))
      this.currentUser = this.users[0]
      this.getStores()
      this.getCountInfo()
      this.getScoreInfo()
      this.getOrderCount()
    })
  },
  methods: {
    isAdmin() { return this.roles.includes('admin') },
    setUsers() {
      const noPidUsers = this.allUser.filter(item => !item.pid)
      this.noPidUsers = noPidUsers.filter(item => {
        for (let i = 0; i < this.allUser.length; i++) {
          if (this.allUser[i].pid === item.id) {
            return false
          }
        }
        return true
      })
      this.users = toTree(this.allUser)
    },
    setUserScore(data) {
      this.$prompt('请输入限额', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'number'
      }).then(({ value }) => {
        setUserScore(data.id, value).then(resp => {
          Message.success('设置成功')
        })
      })
    },
    getStores() {
      fetchStore(this.currentUser.id).then(response => {
        this.stores = response.data.sort((a, b) => a.order_index - b.order_index)
      })
    },
    getCountInfo() {
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      const startDate = dateFormat(start, 'yyyy-mm-dd')
      const endDate = dateFormat(new Date(), 'yyyy-mm-dd')
      getCountInfo(this.currentUser.id, startDate, endDate, endDate).then(response => {
        const info = response.data
        info.currentInterest = this.currentUser.interest_rate * info.currentScore
        this.countInfo = info
      })
    },
    getOrderCount() {
      getUserOrderStatistic(this.currentUser.id).then(response => {
        this.todayOrder.orderNumber = response.data.orderCount
        this.todayOrder.payNumber = response.data.payCount
        this.todayOrder.payRate = response.data.payCount * 100.0 / response.data.orderCount
      })
    },
    getScoreInfo() {
      info(this.currentUser.id).then(response => {
        this.scoreInfo.allScore = response.data.allScore / 100
        this.scoreInfo.allSuccessScore = response.data.allSuccessScore / 100
        this.scoreInfo.runScore = response.data.runScore / 100
        this.scoreInfo.runSuccessScore = response.data.runSuccessScore / 100
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleNodeClick(event, data) {
      this.goodses = []
      this.currentUser = data.data
      this.parentUser = data.parent ? data.parent.data : {}
      this.getStores()
      this.getCountInfo()
      this.getScoreInfo()
      this.getOrderCount()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    changeInterestRate() {
      this.$prompt(`请输入利率(${this.parentUser.interest_rate || ''}%${this.parentUser.interest_rate ? '以下' : ''})`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'number',
        inputPattern: /^\d+(\.{0,1}\d+){0,1}$/,
        inputValidator: (val) => {
          if (val > this.parentUser.interest_rate) {
            return `利率必须小于等于${this.parentUser.interest_rate}%`
          }
        },
        inputErrorMessage: `利率不能小于0`
      }).then(({ value }) => {
        setInterestRate({ 'id': this.currentUser.id, 'interestRate': value }).then(response => {
          Message.success('更改成功')
          this.allUser = this.allUser.map(item => {
            if (item.id === this.currentUser.id) {
              item.interest_rate = value
            }
            return item
          })
          this.setUsers()
          this.$refs.tree.setCurrentKey(this.currentUser.id)
        })
      })
    },
    handleDialogStoreClose() {
      this.selectedValue = []
      this.selectStores = []
    },
    getSelectStore(query) {
      queryNoUserId(query).then(response => { this.selectStores = response.data })
    },
    addStoresToUser() {
      setUserId(this.selectedValue, this.currentUser.id)
        .then(_ => {
          // 重新获取用户商店并且刷新选择信息
          this.getStores()
          this.selectStores = []
          this.selectedValue = []
        })
    },
    removeStore(id) {
      removeUserId(id).then(_ => this.getStores())
    },
    startAll() {
      startAllStore(this.currentUser.id).then(() => {
        Message.success('操作成功')
        this.getStores()
        this.getScoreInfo()
      })
    },
    stopAll() {
      stopAllStore(this.currentUser.id).then(() => {
        Message.success('操作成功')
        this.getStores()
        this.getScoreInfo()
      })
    },
    setScore() {
      if (this.multipleSelection.length === 0) {
        Message.warning('请选择数据!')
        return
      }
      this.$prompt('请输入限额（元）', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '只能输入数字'
      }).then(({ value }) => {
        const userScore = this.currentUser.score
        const score = this.multipleSelection.length * value
        if (score > userScore) {
          Message.warning({
            message: `超出总限额，
          指定店铺数量：${this.multipleSelection.length},
          您的限额： ${score}, 
          上级指定总限额：${userScore}`,
            duration: 5000
          })
          return
        }
        setScore(this.multipleSelection.map(i => i.id), value * 100).then(_ => {
          Message.success('操作成功')
          this.getStores()
          this.getScoreInfo()
        })
      })
    },
    setUserPause(data) {
      setPause(data.id, data.pause === 0 ? 1 : 0).then(resp => {
        Message.success('操作成功')
        this.$set(data, 'pause', data.pause === 0 ? 1 : 0)
      })
    },
    toggleStoreLoop(row) {
      setLoop(row.id, row.loop, this.currentUser.id).then(response => {
        Message.success('设置成功')
        this.getStores()
        this.getScoreInfo()
      })
    },
    toggleGoodsLoop(row) {
      setGoodsLoop(row.id, row.loop).then(response => Message.success('设置成功'))
    },
    handleStoreRowClick(row) {
      getGoodsList({
        store_id: row.id,
        page: 1,
        limit: 50
      }).then(response => {
        this.goodses = response.data.list
      })
    },
    handleEditStore(row) {
      this.formEditStore.score = row.score / 100
      this.formEditStore.loop = `${row.loop}`
      this.formEditStore.old_loop = `${row.loop}`
      this.formEditStore.userId = this.currentUser.id
      this.formEditStore.storeId = row.id
      this.dialogModifyStoreVisible = true
    },
    submitFormEditStore() {
      editStore(this.formEditStore).then(resp => {
        Message.success('操作成功')
        this.getStores()
        this.getScoreInfo()
        this.dialogModifyStoreVisible = false
      })
    }
  }
}
</script>
<style scoped>
.score-status-red{
  color: red;
}
.tag-wrapper{
  padding-top: 16px;
}
.tag-small{
  margin-right: 8px;
  margin-bottom: 8px;
}
.tree {
  margin-top: 8px;
  /* background: #F0F9EB; */
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.toop-bar {
  display: flex;
  flex-direction: row-reverse;
  padding-bottom: 8px;
  padding-right: 8px;
}
.score-info{
  font-size: 12px;
}
.card {
  height: 170px;
}
.score-info-current {
    color: #67C23A;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
